package com.dwb.utils;

import com.dwb.entity.SGoodsCategory;
import com.dwb.vo.NodeVo;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeUtil {

    public static Map<String, NodeVo> nodeDataToTree(List<SGoodsCategory> list) {
        String[] matchs = new String[list.size()];
        String id;
        String parentId;
        int i = 0;
        Map<String, NodeVo> map = new HashMap<>();
        map.put(String.valueOf(0), new NodeVo());
        map.get(String.valueOf(0)).setChildren(new ArrayList<>());
        for (SGoodsCategory p : list) {
            NodeVo vo = new NodeVo();
            BeanUtils.copyProperties(p, vo);
            map.put(String.valueOf(vo.getId()), vo);
            if (vo.getChildren() == null) {
                vo.setChildren(new ArrayList<NodeVo>());
            }
            if (vo.getPid() == null || "".equals(vo.getPid())) {
                vo.setPid(0);
            }
            matchs[i++] = vo.getId() + ":" + vo.getPid();
        }
        for (String match : matchs) {
            id = match.split(":")[0];
            parentId = match.split(":")[1];
            if (null != map.get(parentId)) {
                if (null == map.get(parentId).getChildren()) {
                    map.get(parentId).setChildren(new ArrayList<>());
                }
                map.get(parentId).getChildren().add(map.get(id));
            }
        }
        return map;
    }
}
